<template>
  <div ref="refMonacoContainer" style="height: 200px; width: 100%; border: 1px solid #bbbbbb"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as monaco from 'monaco-editor'

const props = defineProps({
  value: {
    type: String,
    default: ''
  },
  readonly: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:value'])

let editor = null
const refMonacoContainer = ref()

const initMonaco = () => {
  console.log(props.value, 'props.value')
  console.log(monaco, 'monaco')
  if (!refMonacoContainer.value) {
    editor = {}
  }
  if (editor) {
    return
  }
  editor = monaco.editor.create(refMonacoContainer.value, {
    value: props.value,
    language: 'java',
    theme: 'hc-black', // 主题
    folding: true, // 是否折叠
    foldingHighlight: true, // 折叠等高线
    foldingStrategy: 'indentation', // 折叠方式  auto | indentation
    showFoldingControls: 'always', // 是否一直显示折叠 always | mouseover
    disableLayerHinting: true, // 等宽优化
    emptySelectionClipboard: true, // 空选择剪切板
    selectionClipboard: true, // 选择剪切板
    automaticLayout: true, // 自动布局
    codeLens: true, // 代码镜头
    scrollBeyondLastLine: false, // 滚动完最后一行后再滚动一屏幕
    colorDecorators: true, // 颜色装饰器
    accessibilitySupport: 'on', // 辅助功能支持  "auto" | "off" | "on"
    lineNumbers: 'on', // 行号 取值： "on" | "off" | "relative" | "interval" | function
    lineNumbersMinChars: 5, // 行号最小字符   number
    readOnly: props.readonly, // 是否只读  取值 true | false
    lineDecorationsWidth: 10
  })

  // 监听内容变化
  editor.onDidChangeModelContent(() => {
    emit('update:value', editor.getValue())
  })
  console.log(editor, '监听内容变化')
  // 监听失去焦点事件
  editor.onDidBlurEditorText(() => {
    console.log(editor.getValue())
  })
  // // 监听内容变化
  // editor.onDidChangeModelContent((e) => {
  //   console.log(editor.getValue(), "");
  //   // data.form.constraint = editor.getValue();
  //   // console.log(editor.getValue());
  // });
  // // console.log(editor, "监听内容变化");
  // // 监听失去焦点事件
  // editor.onDidBlurEditorText(() => {
  //   console.log(editor.getValue());
  // });
}

// watch(
//   () => props.value,
//   (newValue) => {
//     if (editor) {
//       editor.setValue(newValue);
//     }
//   }
// );

const setValue = (value) => {
  if (editor) {
    editor.setValue(value)
  }
}

onBeforeUnmount(() => {
  if (editor) {
    editor.dispose()
  }
})

onMounted(() => {
  initMonaco()
})

defineExpose({
  initMonaco,
  setValue
})
</script>

<style></style>
